package cn.wolfcode.web.controller;

import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    IEmployeeService service;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session) {
        try {
            //传入登录用户的账户和密码,创建令牌对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //获取当前的用户主体对象,调用登录验证方法(token会进入realms(数据源)的doGetAuthenticationInfo方法进行验证)
            SecurityUtils.getSubject().login(token);
            return new JsonResult(true, "登陆成功");
        } catch (UnknownAccountException e) {
            //根据源码分析,会先验证账号是否存在
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (DisabledAccountException e) {
            return new JsonResult(false, "账号被禁用,请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }
    }

}
